package com.sks.service.house.impl;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

import javax.annotation.Resource;

import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.sks.bean.pojo.AuditHistory;
import com.sks.dao.house.AuditHistoryDao;
import com.sks.service.base.BaseService;
import com.sks.service.house.AuditHistoryService;
import com.sks.utils.StringUtil;

@Service
@Transactional
public class AuditHistoryServiceBean extends BaseService<AuditHistory> implements AuditHistoryService {
	@Resource(name = "auditHistoryDao")
	public void setAuditHistoryDao(AuditHistoryDao auditHistoryDao) {
		this.setDao(auditHistoryDao);
	}
	
	public List<AuditHistory> findByObjType(String objType) {
		StringBuffer hql = new StringBuffer("select ah from AuditHistory ah ");
		Object[] params = null;
		if (!StringUtil.isEmpty(objType)) {
			hql.append(" where objType = ? ");
			params = new Object[]{objType};
		}
		hql.append(" order by ts desc ");
		return this.getListByJpql(hql.toString(), params);
	}
	
	@Override
	public int getCountByDate(Date fromDate, Date toDate) {
		try {
			StringBuffer hql = new StringBuffer(
					"select count(ah.ahId) from AuditHistory ah where 1 = 1 ");
			List params = new ArrayList();
			if (null != fromDate) {
				hql.append(" and ah.ts >= ? ");
				params.add(fromDate);
			}
			if (null != toDate) {
				hql.append(" and ah.ts <= ? ");
				params.add(toDate);
			}
			return ((Long) this.getObjectByJpql(hql.toString(), params
					.toArray())).intValue();
		} catch (Exception e) {
			e.printStackTrace();
			return 0;
		}
	}
	
	@Override
	public int getCountByDate(Date date) {
		if (date == null) {
			return 0;
		}
		Calendar c = Calendar.getInstance();
		c.setTime(date);
		c.set(Calendar.HOUR_OF_DAY, 0);
		c.set(Calendar.MINUTE, 0);
		c.set(Calendar.SECOND, 0);
		Date fromDate = c.getTime();
		c.set(Calendar.HOUR_OF_DAY, 23);
		c.set(Calendar.MINUTE, 59);
		c.set(Calendar.SECOND, 59);
		Date toDate = c.getTime();
		return this.getCountByDate(fromDate, toDate);
	}
}
